#include <cstdio>
#include <iostream>
#include <csignal>

#include "common/log.hpp"
#include "common/MyIP.hpp"
#include "udp/UDPPinger.hpp"
#include "udp/UDPListener.hpp"
#include "tcp/TCPMessenger.h"
#include "tcp/TCPListener.h"
#include "TCPMessageCounter.hpp"

#include "GlobalObjects.hpp"

#include "file-client/FileClient.hpp"


const int default_port = 8080;

using namespace efs;

const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = "efs";

const int item_count = 10;
UDPPinger *pingers[item_count];
UDPListener *listeners[item_count];
TCPListener *tcp_listeners[item_count];
TCPMessenger *tcp_messengers[item_count];
ClientEntryList clients[item_count];

TCPMessageCounter counter;


bool stop_request = false;

void sigHandler (int sigNum)
{
	pantheios::log_INFORMATIONAL("CTRL-C signal");
	for (int i = 0; i < item_count; ++i)
	{
		pingers[i]->stop();
		listeners[i]->stop();
		tcp_listeners[i]->stopListening();
	}
	stop_request = true;
}

int main(int argc, char *argv[])
{
	MyIP my_ip;

	Settings settings;
	settings.udp_port = 1234;
	settings.ping_period = 1;
	settings.my_net_settings.ip = my_ip.getMyIP();
	for (int i = 0; i < item_count; ++i)
	{
		settings.my_net_settings.file_port = 8000 + i;
		settings.my_net_settings.tcp_port = 3000 + i;
		pingers[i] = new UDPPinger(settings);
		listeners[i] = new UDPListener(settings, &clients[i]);

		tcp_listeners[i] = new TCPListener(settings.my_net_settings.tcp_port);
		tcp_messengers[i] = new TCPMessenger(&clients[i]);
		tcp_listeners[i]->setSubscriber(&counter);
	}


	//TCPListener;
	//TCPMessenger *tcp_messenger;

	signal(SIGINT, sigHandler);
	settings.loadCommandLine(argc, argv);

	pantheios::log_INFORMATIONAL("Start");

	for (int i = 0; i < item_count; ++i)
	{
		pingers[i]->start();
		listeners[i]->start();
		tcp_listeners[i]->startListening();
	}

	sleep(3);
	std::string msg = "123";
	//tcp_messengers[0]->sendMessages(msg);


	for (int i = 0; i < item_count; ++i)
	{
		tcp_messengers[i]->sendMessages(msg);
	}

	std::cout << "123" << std::endl;

	for (int i = 0; i < item_count; ++i)
	{
		tcp_messengers[0]->sendMessages(msg);
	}

	while (!stop_request)
	{
		sleep(1);
		//std::cin >> msg;
		//tcp_messengers[0]->sendMessages(msg);
	}

	clients[0].print();
	pantheios::log_INFORMATIONAL("Exit");

	for (int i = 0; i < item_count; ++i)
	{
		delete pingers[i];
		delete listeners[i];

		delete tcp_listeners[i];
		delete tcp_messengers[i];
	}

	std::cout << counter.m_count << std::endl;

	return 0;
}

